<?php
/*
 * IKPHP 爱客开源社区 @copyright (c) 2012-3000 IKPHP All Rights Reserved 
 * @author 小麦
 * @Email:ikphp@sina.cn 2014年8月27日16:58:00
 * @小组应用
 */
namespace IKPHP\Apps\Group\Controllers;

use IKPHP\Apps\Group\Controllers;
use IKPHP\Common\Models\User;
use IKPHP\Apps\Group\Models\Group;
use IKPHP\Apps\Group\Models\GroupCate;
use IKPHP\Org\UploadFile;
use IKPHP\Apps\Group\Models\GroupUsers;

class ManageController extends GroupBaseController
{
	private $userid = 0;
	
    public function initialize()
    {
        parent::initialize();
        // 访问者控制
		if ($this->visitor){
			$this->userid = $this->visitor['userid'];
		}        
    }
    private function _init_editmenu($groupid){
		//生成菜单
		$menu = array(
				'edit' => array('text'=>'基本信息', 'url'=>U('group/manage/edit/'.$groupid)),
				'editicon' => array('text'=>'小组图标', 'url'=>U('group/manage/editicon/'.$groupid)),
				'members' => array('text'=>'成员管理', 'url'=>U('group/manage/members/'.$groupid)),
		);  
		$this->assign('menu',$menu);  
    }
    private function _makeData($isCreate = true){
		//组合数据	
		$data ['userid'] = $this->userid;	
		$data ['groupname'] = $groupname = ikwords ( $this->_post ( 'groupname' ) ); 
		$data ['groupdesc'] = ikwords ( $this->_post ( 'groupdesc' ) );
		$data ['cateid']    = $this->_post ( 'twoid', 'trim,intval', 0 );

		$isCreate ? $data ['addtime'] = time () : $data ['uptime'] = time ();
	
		//小组名唯一
		if(Group::gname_exists($groupname) && $isCreate){
			return $this->error ( '该小组名太火爆；已经被使用；换个别的吧' );
		}
		if(ck_strlen($data ['groupname']) > 32 || ck_strlen($data ['groupname']) < 2){
			return $this->error ( '小组标题必须填写；且必须在2-30个字以内' );
		}
		if(ck_strlen($data ['groupdesc']) < 10){
			return $this->error ( '小组描述太少了必须大于10个字，多多益善^_^' );
		}
		if(ck_strlen($data ['groupdesc']) > 10000){
			return $this->error ( '写这么多内容干啥，超出1万个字了都^_^' );
		}				
		if(empty($data ['cateid'])){
			return $this->error ( '小组子分类选择必须选择' );
		} 
		return $data;   
    }
    //创建小组
    public function createAction(){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;
		
    	if(IS_POST){
    		if ($this->security->checkToken()) {
    			if ($_POST ['grp_agreement'] != 1) return $this->error ( '不同意社区指导原则是不允许创建小组的！' );
	    				
				$data = $this->_makeData();				

				$group = new Group();
				//开始创建
				if(false !== $group->create ( $data )){
					 $groupid = $group->groupid;
					 //图标
					 if ($this->request->hasFiles() == true) {
						 	$up_files = $this->request->getUploadedFiles();
						 	$groupicon = $up_files[0];	
						 	//只有jpg和png可以做图标
						 	if($groupicon->getType()=='image/jpeg' || 'image/png'==$groupicon->getType()){			
						 		//保存文件夹
					            $save_dir = 'group/icon/';	
								//开始保存
								$upload = new UploadFile(array('autoSub'=>false,'savePath'=>$save_dir,'saveName'=> md5($groupid)));
								$result = $upload->upload();
								if(!empty($result)){
									//生成缩略图
									$imgpath = C('ik_attach_path').$result[0]['savefile'];
									$image = new \IKPHP\Org\Image();
													
									$arr_size = array(48,60,200);         
						            //打开图像
						            foreach ($arr_size as $item){
						            	$image->open($imgpath);
						            	$thumb_name = $result[0]['filename'].'_'.$item.'_'.$item.'.'.$result[0]['ext']; //文件名
						            	$thumb_img = C('ik_attach_path').$result[0]['savepath'].$thumb_name;//保存路径
						            	if($item == 200){
						            		$image->thumb($item, $item)->save($thumb_img);
						            	}else{
						            		$image->thumb($item, $item, 6)->save($thumb_img);
						            	}
						            }								
									//保存
									$group->groupicon = $result[0]['savename'];
									$group->save();
								}								
						 	}
					 }
					
					return $this->_redirect('group/show/'.$groupid);
					 
				}else{
					return $this->error($group->getMessages());
				}
				
    		}else{
    			return $this->error ( '呃...已经超时了' );
    		}
    	}else{	
    		//判断权限
			if (C ( 'ik_iscreate' ) == 1) return $this->error ( '您好，网站暂时关闭创建小组；如有疑问联系站长！' );
			//获取该用户已经创建了多少个小组
			$maxgroup = Group::count("userid = '$userid'"); 
			if ($maxgroup >= C ( 'ik_maxgroup' )) return $this->error ( '您好，您的积分不够，最多只能创建' . $maxgroup . '个小组！' );
			
			//分类
			$arrOne = GroupCate::getCates();
			$this->assign ( 'arrOne', $arrOne );
										
			$this->_config_seo ( array (
					'title' => '申请创建小组',
					'subtitle'=>'小组_'.C('ik_site_title'),
					'keywords' =>'',
					'description'=>'',
			) );			
    	}    	
    }
	//ajax获取子分类
	public function ajax_getcateAction() {
		$oneid = $this->_post ( 'oneid', 'trim,intval' );
		$arrCate = GroupCate::getReferCate ( $oneid );
		if ($arrCate) {
			echo '<select id="twoid" name="twoid" class="txt">';
			echo '<option value="0">请选择</option>';
			foreach ( $arrCate as $item ) {
				echo '<option value="' . $item ['cateid'] . '">' . $item ['catename'] . '</option>';
			}
			echo "</select>";
		} else {
			echo '';
		}
		$this->view->disable();
	}    
    //编辑小组
    public function editAction($id =''){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;

		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		$strGroup = Group::getOneGroup ( $id );
		if(empty($strGroup)) return $this->error ( '呃...你想要的东西不在这儿' );
		
    	if($userid != $strGroup['userid']){
			return $this->error('您没有权限编辑小组信息！');
		}
		
		if(IS_POST){
			if($this->security->checkToken()){
				$data = $this->_makeData(false);
				$group_mod = new Group();
				$res = $group_mod->findFirst(array('conditions'=>"groupid = '$id' AND userid='$userid'"))->save($data);
				if($res){
					$this->_redirect('group/show/'.$id);
				}else{
					return  $this->error ( '更新失败' );
				}	
						
			}else{
				return $this->error ( '呃...已经超时了' );
			}
		}else{
		    $this->_init_editmenu($id);
			//分类
			$arrOne = GroupCate::getCates();
			$strCate = GroupCate::getOneCate ( $strGroup['cateid'] ); 
			$arrTwo = GroupCate::getReferCate ( $strCate['referid'] );
			$this->assign ( 'arrOne', $arrOne );
			$this->assign ( 'arrTwo', $arrTwo );
			$this->assign ( 'strCate', $strCate );
			
			$this->assign('strGroup',$strGroup);
			$this->_config_seo ( array (
					'title' => '编辑小组基本信息',
					'subtitle'=>'小组_'.C('ik_site_title'),
					'keywords' =>'',
					'description'=>'',
			) ); 		
		}   	
    }
    //编辑小组图标
    public function editiconAction($id=''){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;

		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		$strGroup = Group::getOneGroup ( $id );
		if(empty($strGroup)) return $this->error ( '呃...你想要的东西不在这儿' );

        if($userid != $strGroup['userid']){
			return $this->error('您没有权限编辑小组信息！');
		}		
		
		if (IS_POST && $this->security->checkToken()) {
		
				if($this->request->hasFiles() == true){
				//类型判断
				$up_files = $this->request->getUploadedFiles();
				$up_file = $up_files[0];
				$up_file_type = $up_file->getType();
				
				
				//类型判断
				if($up_file_type !== 'image/png' && $up_file_type !== 'image/jpeg')
				{
					$this->flashSession->error('<div class="faceerror">图像类型不符；只允许上传jpeg、jpg、png类型图片</div>');
					return $this->_redirect('group/manage/editicon/'.$id);		
				}
					
				//尺寸判断
				$imageinfo = @getimagesize($_FILES['picfile']['tmp_name']);
				if($imageinfo[0] < 200 || $imageinfo[1] < 200)
				{
					$this->flashSession->error('<div class="faceerror">图像请勿小于: 200 x 200</div>');
					return $this->_redirect('group/manage/editicon/'.$id);						
				}				
				//大小判断
				if($up_file->getSize()/1024 > 1024)
				{
					$this->flashSession->error('<div class="faceerror">头像不允许大于1024KB</div>');
					return $this->_redirect('group/manage/editicon/'.$id);						
				}
				
				//会员头像保存文件夹
	            $avatar_dir = 'group/icon/';
			            
				$upload = new UploadFile(array('autoSub'=>false,'savePath'=>$avatar_dir,'saveName'=> md5($id)));
				$result = $upload->upload();
				if($result){
					
					$imgpath = C('ik_attach_path').$result[0]['savefile'];
					$image = new \IKPHP\Org\Image();
					//打开图像生成thumb
					try {
						//获取配置头像大小
						$arr_face_size = array(48,60,200);            
			            //打开图像
			            foreach ($arr_face_size as $item){
			            	$image->open($imgpath);
			            	$thumb_name = $result[0]['filename'].'_'.$item.'_'.$item.'.'.$result[0]['ext']; //文件名
			            	$thumb_img = C('ik_attach_path').$result[0]['savepath'].$thumb_name;//保存路径	            	
			            	if($item == 200){
			            		$image->thumb($item, $item)->save($thumb_img);
			            	}else{
			            		$image->thumb($item, $item, 6)->save($thumb_img);
			            	}
			            }
			            //更新数据库
			            $group = Group::findFirst("groupid='$id'");
			            $group->groupicon = $result[0]['savename'];
			            
			            if($group->save()){
			            	$this->flashSession->success('<div class="facesuccess">小组图标上传成功；随意拖拽或缩放大图中的虚线方格，预览的小图即为保存后的小图标</div>');
			            	return $this->_redirect('group/manage/editicon/'.$id);	
			            }
			            
					} catch(\Exception $e) {
						return $this->error($e->getMessage());
					}

				}else{
					return $this->error($upload->getError());
				}
			}else{
				$this->flashSession->error('<div class="faceerror">你没有选择图像文件</div>');
				return $this->_redirect('group/manage/editicon/'.$id);		
			}				
			
		}
		
		if(!$strGroup['groupicon']){
			$strGroup['icon_200'] = C('ik_site_url') . 'static/images/group.jpg';
		}else{
			$filename = explode('.', $strGroup['groupicon']);
			$imgpath = C('ik_attach_path').'group/icon/'.$strGroup['groupicon'];
		    $thumb_name = $filename[0].'_200_200.'.$filename[1]; //文件名	
			$thumb_img = C('ik_attach_path').'group/icon/'.$thumb_name;//保存路径
			if(is_file($thumb_img)){
				$strGroup['icon_200'] = attach('group/icon/'.$thumb_name);
			}else{
				$image = new \IKPHP\Org\Image();         	
				$image->open($imgpath);	
				$image->thumb(200, 200)->save($thumb_img);	
				$strGroup['icon_200'] = attach('group/icon/'.$thumb_name);		
			}
		}
		
		$this->_init_editmenu($id);
		$this->assign('strGroup',$strGroup);
 		$this->_config_seo ( array (
				'title' => '添加或更改小组的大头像',
				'subtitle'=>'小组_'.C('ik_site_title'),
				'keywords' =>'',
				'description'=>'',
		) );    	
    }
	//保存小图像
	public function seticonsmallAction($id=''){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}
		$userid = $this->userid;
		
		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		$strGroup = Group::getOneGroup ( $id );
		if(empty($strGroup)) return $this->error ( '呃...你想要的东西不在这儿' );

        if($userid != $strGroup['userid']){
			return $this->error('您没有权限编辑小组信息！');
		}	
				
		if(IS_POST){
			$imgpos = $this->_post('imgpos');
			$imgpos = explode('_', $imgpos);
			//判断是否拖动
			if((int)$imgpos[2] < 48 ){
            	$this->flashSession->success('<div class="faceerror">图片缩放的太小了；请重新取样缩放；宽度不小于48px！</div>');
            	return $this->_redirect('group/manage/editicon/'.$id);							
			}
			//先判断是否存在
			if(empty($strGroup['groupicon'])){
            	$this->flashSession->success('<div class="faceerror">你还没有上传图像文件；请先上传一个图像文件吧！</div>');
            	return $this->_redirect('group/manage/editicon/'.$id);					
			}
			
			//开始切割
			
			$arrfilename = explode('.', $strGroup['groupicon']);
			$img_name = $arrfilename[0];
			$img_ext = $arrfilename[1];
			
			$imgpath = C('ik_attach_path').'group/icon/'.$img_name.'_200_200.'.$img_ext;
			if(!is_file($imgpath)){
            	$this->flashSession->success('<div class="faceerror">服务器无法找到图像文件；请先上传一个图像文件吧！</div>');
            	return $this->_redirect('group/manage/editicon/'.$id);			
			} 
			$image = new \IKPHP\Org\Image();
			//打开图像生成thumb
			try {
				//获取配置头像大小
				$arr_face_size = array(48,60);     
	            //打开图像
	            foreach ($arr_face_size as $item){
	            	$image->open($imgpath);
	            	$thumb_name = $img_name.'_'.$item.'_'.$item.'.'.$img_ext; //文件名
	            	$thumb_img = C('ik_attach_path').'group/icon/'.$thumb_name;//保存路径
	            	$image->crop($imgpos[2], $imgpos[2], $imgpos[0], $imgpos[1],$item,$item)->save($thumb_img);
	            }
				//成功跳转
	            return $this->_redirect('group/show/'.$id);	
	            
			} catch(\Exception $e) {
				return $this->error($e->getMessage());
			}			
			
		}else{
			return $this->error('你访问的页面不存在！');
		}
	}    
	// 加入小组
	public function joinAction($id ='') {
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;
		$groupid = $id;
		
		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		$strGroup = Group::getOneGroup ( $id );
		if(empty($strGroup)) return $this->error ( '呃...你想要的东西不在这儿' );

		// 先统计用户有多少个小组了，20个封顶
		$userGroupNum = GroupUsers::count("userid = '$userid'");
		
		if ($userGroupNum >= C ( 'ik_jionmax' ))
			return $this->error ( '你加入的小组总数已经到达' . $userGroupNum . '个，不能再加入小组！' );
		
		$groupUserNum = GroupUsers::count("userid = '$userid' and groupid='$groupid'");
		if ($groupUserNum > 0)
			return $this->error ( '你已经加入小组！' );
		
		// 执行加入
		$data = array ('userid' => $this->userid, 'groupid' => $groupid, 'isadmin' => 0,  'addtime' => time () );
		$groupuser = new GroupUsers();
		if (false !== $groupuser->create ( $data )) {
			$refer = $this->_get('refer');
			if(!empty($refer)){
				$this->_redirect ( $refer );
			}else{
				$this->_redirect ( 'group/show/'.$groupid );
			}
		}else{
			return $this->error ( $groupuser->getMessages() );
		}
	
	}
	//退出小组
	public function quitAction($id =''){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;
		$groupid = $id;
		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
			
		//判断是否是组长，是组长不能退出小组
		$strGroup = Group::getOneGroup ( $groupid );
		if ($strGroup ['userid'] == $userid) {
			return $this->error ( '组长任务艰巨，请坚持到底！' );
		}
		//开始退出
		$is_del = GroupUsers::findFirst("userid = '$userid' AND groupid = '$groupid' ")->delete();
		
		if($is_del){
			$this->_redirect ( 'group/show/'.$groupid );
		}else{
			return $this->error ( '退出失败~' );
		}
	}
	//管理加入小组的成员
	public function membersAction($id = ''){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}  
		$userid = $this->userid;

		if(!is_numeric($id) || empty($id)){
			return $this->error('呃...你想访问的页面不存在');
		}	
		$strGroup = Group::getOneGroup ( $id );
		if(empty($strGroup)) return $this->error ( '呃...你想要的东西不在这儿' );
		
    	if($userid != $strGroup['userid']){
			return $this->error('您没有权限编辑小组信息！');
		}
		
		
		//小组组长信息
		$leaderId = $strGroup['userid'];
		$strLeader = User::getOneUser($leaderId);
		$this->assign('strLeader',$strLeader);
			
		//管理员信息
		$arrAdmin =  GroupUsers::getAdmins($id); 
		$this->assign('arrAdmin',$arrAdmin);
		
		//小组会员
		$arrGroupUser = GroupUsers::getGroupUser($id); 
		$this->assign('arrGroupUser', $arrGroupUser);
		
 		$this->_init_editmenu($id);
		$this->assign('strGroup',$strGroup);
		$this->_config_seo ( array (
				'title' => '小组成员管理 ',
				'subtitle'=>'小组_'.C('ik_site_title'),
				'keywords' =>'',
				'description'=>'',
		) ); 				
	}
	public function roleforAction($type){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');} 
						
		$userid  = $this->_get( 'uid', 'intval'); 
		$groupid = $this->_get( 'gid', 'intval');				
		if (! empty ( $type ) && $userid>0 && $groupid>0) {
			$strGroup = Group::getOneGroup ( $groupid );
			if(empty($strGroup)) return $this->error ( '机房重地，闲人免进' );
			//自己无法提升自己
			if($strGroup['userid'] == $userid) return $this->error ( '你是无法操纵自己的' );
			//非组长不能
			if($strGroup['userid'] != $this->userid) return $this->error ( '您没有权限操作' );
			
			switch ($type) {
				// 取消管理员
				case "cancel_admin" :
						GroupUsers::findFirst("groupid='$groupid' and userid='$userid'")->save(array('isadmin'=>0));
					break;
				// 提升为管理员
				case "promote_admin":
						GroupUsers::findFirst("groupid='$groupid' and userid='$userid'")->save(array('isadmin'=>1));
					break;
				// 踢出小组
				case "kick":
						GroupUsers::findFirst("groupid='$groupid' and userid='$userid'")->delete();
					break;							
				// 默认
				default :
					return $this->error ( '呃...你想要的东西不在这儿' );			
			}
			$this->_redirect ( 'group/manage/members/'.$groupid);	
		}else{
			return $this->error('呃...你想访问的页面不存在');
		}	
	}
}